from django.shortcuts import render, redirect, HttpResponse
from django.urls import reverse
from django.http import JsonResponse
from web import models
from web.forms.wiki import WikiAddModelForm
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings


# Wiki文章详情页面
def wiki(request, project_id):
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, 'wiki.html', {'wiki_object': wiki_object})


# 添加Wiki文章
def wiki_add(request, project_id):
    if request.method == "GET":
        form = WikiAddModelForm(request)
        return render(request, 'wiki_form.html', {'form': form, 'request': request})
    form = WikiAddModelForm(request, data=request.POST)
    if form.is_valid():
        # 判断是否选择了父文章，
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
    return redirect(reverse('wiki', kwargs={"project_id": project_id}))


# Wiki文章多级目录
def wiki_catalog(request, project_id):
    wiki_l = models.Wiki.objects.filter(project_id=project_id).values('id', 'title', 'parent_id', 'depth').order_by(
        'depth', 'id')
    return JsonResponse({'status': True, 'data': list(wiki_l)})


# 编辑Wiki文章
@csrf_exempt
def wiki_edit(request, project_id, wiki_id):
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == "GET":
        form = WikiAddModelForm(request, instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiAddModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        # 给表单实例对象的project_id赋值
        form.instance.project_id = project_id
        # 判断是否选择了父文章，
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        # url = reverse('wiki', kwargs={'project_id': project_id})
        # preview_url = "{0}?wiki_id={1}".format(url, wiki_id)
        # return redirect(preview_url)
        return redirect(reverse('wiki', kwargs={'project_id': project_id}) + '?wiki_id=' + wiki_id)
    return render(request, 'wiki_form.html', {'form': form})


# 删除Wiki文章
def wiki_delete(request, project_id, wiki_id):
    url = reverse('wiki', kwargs={'project_id': project_id})
    # wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    # if not wiki_object:
    #
    #     return redirect(url)
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    return redirect(url)


# wiki文章图片上传
@csrf_exempt
def wiki_uploads(request, project_id, wiki_id):
    import web
    import os
    # 获取POST提交过来的文件
    file = request.FILES.get("editormd-image-file")
    # 获取图片文件的后缀
    suffix = os.path.splitext(file.name)[-1]
    # 重新定义图片文件名，避免重名 4_13_1670401656410.jpg
    file_name = project_id + "_" + wiki_id + "_" + request.GET.get("guid") + suffix
    # 构造图片路径 /static/uploads/img/4_13_1670401656410.jpg
    file_url = settings.UPLOADS_DIR + file_name
    # 获取当前app 即web的路径 D:\pythonProject\bugtracer\web
    app_path = os.path.dirname(web.__file__)
    # 构造图片的存储路径 D:\pythonProject\bugtracer\web/static/uploads/img/4_13_1670401656410.jpg
    storage_filename = app_path + file_url
    print(file, app_path + file_url, "-----------wiki_id:", request.GET.get("wiki_id"))
    # 文件存储
    with open(storage_filename, 'wb') as f:
        for i in file:
            f.write(i)
    return JsonResponse({'success': 1, 'message': "图片上传成功", 'url': file_url})
